//
//  GoodsDetailsViewController.m
//  WZCLApp
//
//  Created by chirui on 2018/7/7.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "GoodsDetailsViewController.h"
#import "MyCenterCViewCell.h"
#import "MyCenterCollectionReusableView.h"
#import "ShopFootCReusableView.h"
#import "GoodsWebCollectionViewCell.h"
#import "SureOrderViewController.h"

@interface GoodsDetailsViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,SDCycleScrollViewDelegate,UITextFieldDelegate,UIWebViewDelegate>{
    
    UICollectionView * _collectionView;
    NSMutableArray * _dataArray;
    NSDictionary * dataDic;
    int _page;
    int _totailPage;
    int num; //购买数量
    int allNumber; // 总库存
    int currayIndex;
     UIButton * backBtn;
     UILabel * price;
    UILabel * goodsTypeLabel;
    NSString * optionNameStr;
    
    UILabel * numberLabel;
    UIView * alertBgView;
    UILabel * priceLabel;  // 商品价格
    UILabel * kuCunNumber; // 库存
    NSString * ChooseGoodsOption;  //选择类型
    
    UIScrollView * scrollView;
    UIView * tagView;
    
    NSString * option_id; //商品属性id

    
    UIWebView * _webView;
    NSInteger height;
}

@end

@implementation GoodsDetailsViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:NO];
    
    self.navigationController.navigationBarHidden = YES; //隐藏
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    
    backBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(8, 20, 35, 35);
    if (ISPX) {
        backBtn.frame = CGRectMake(8, 32, 35, 35);
    }
    
    [backBtn setBackgroundImage:ImageName(@"icon_return_back") forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [window addSubview:backBtn];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    
    self.navigationController.navigationBarHidden = NO; //隐藏
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img_nav_bg"] forBarMetrics:UIBarMetricsDefault];
    [backBtn removeFromSuperview];
}

// 底部按钮UI
-(void)creatDownView {
    
    UIView * downView =[[UIView alloc]initWithFrame:CGRectMake(0, HEIGHT-48, WIDTH, 48)];
    
    UIButton * addCat = [UIButton buttonWithType:UIButtonTypeCustom];
    addCat.frame = CGRectMake(10, 5, WIDTH/2-20, 40);
    [addCat setBackgroundImage:ImageName(@"icon_botton__shop_blue") forState:UIControlStateNormal];
    [addCat setTitle:@"加入购物车" forState:UIControlStateNormal];
    [addCat addTarget:self action:@selector(addCartClick:) forControlEvents:UIControlEventTouchUpInside];
    [downView addSubview:addCat];
    
    
    UIButton * buyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    buyBtn.frame = CGRectMake(WIDTH/2+10, 5, WIDTH/2-20, 40);
    [buyBtn setBackgroundImage:ImageName(@"icon_popup_botton_bg") forState:UIControlStateNormal];
    [buyBtn setTitle:@"立即购买" forState:UIControlStateNormal];
    [downView addSubview:buyBtn];
    [buyBtn addTarget:self action:@selector(buyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    downView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:downView];
    
    
}

-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    num =1;
//    _typeStr = @"1";
    currayIndex = 0;
    optionNameStr = @"";
    
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,WIDTH,50)];
    _webView.scalesPageToFit = YES;
    _webView.delegate = self;
    _webView.scrollView.bounces=NO;
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    _webView.scrollView.scrollEnabled = NO;
   
    [self creatWEB];
    [self creatDownView];
    [self creatCollectionView];
    
    [self getGoodsDetailsRequest];
}


-(void)creatWEB {
    
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:dataDic[@"web_view"][@"detail"]]]];
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] integerValue];
    webView.frame = CGRectMake(0, 0, WIDTH,height);
    
    [_collectionView reloadData];
}

#pragma creatCollectionView

-(void)creatCollectionView {
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, -SH_StatusBarHeight, WIDTH, HEIGHT-SH_TabBarHeight+SH_StatusBarHeight) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:_collectionView];
    _collectionView.showsVerticalScrollIndicator = NO;
    
        MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    
            [self getGoodsDetailsRequest];
    
        }];
        _collectionView.mj_header = header;
    //
    //    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
    //        _page++;
    //
    //
    //    }];
    //
    //    footer.automaticallyRefresh = YES;
    //    _collectionView.mj_footer =footer;
    //
    //    if (_dataArray.count>10) {
    //        _collectionView.mj_footer.hidden = NO;
    //    }else {
    //
    //        _collectionView.mj_footer.hidden = YES;
    //    }
    //
    
    //注册cell类
    [_collectionView registerNib:[UINib nibWithNibName:@"MyCenterCViewCell" bundle:nil] forCellWithReuseIdentifier:@"MyCenterCViewCell"];
    
     [_collectionView registerNib:[UINib nibWithNibName:@"GoodsWebCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"GoodsWebCollectionViewCell"];
    
    
    //    注册header类
    [_collectionView registerClass:[MyCenterCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyCenterCollectionReusableView"];
    // footer
    [_collectionView registerClass:[ShopFootCReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"ShopFootCReusableView"];
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (section==0) {
        return  1;
    }else {
        
        NSArray * array = dataDic[@"product"];
        return array.count;
    }
    
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==1) {
        
   NSArray * array = dataDic[@"product"];
        NSDictionary * dic = array[indexPath.row];
    MyCenterCViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCenterCViewCell" forIndexPath:indexPath];
    cell.clipsToBounds = NO;
    
    //    [cell.goodsImage sd_setImageWithURL:ImageUrl(dic[@"cover_photo"]) placeholderImage:ImageName(@"img_new_default")];
    //
    //    cell.gooseName.frame = CGRectMake(6, CGRectGetMaxY(cell.goodsImage.frame)+5, (WIDTH-10)/2-12, 20);
    //    cell.gooseName.text = dic[@"product_name"];
    //
    //    cell.gooseName.numberOfLines = 2;
    //    [cell.gooseName sizeToFit];
    //
    cell.scoreLabel.text = [NSString stringWithFormat:@"￥%@",@"89.00"];
    cell.scoreLabel.numberOfLines = 1;
    [cell.scoreLabel sizeToFit];
    
    cell.oldPrice.frame = CGRectMake(CGRectGetMaxX(cell.scoreLabel.frame)+5, CGRectGetMinY(cell.scoreLabel.frame)+2, 50, 15);
    cell.oldPrice.numberOfLines = 1;
    [cell.oldPrice sizeToFit];
    [SHJudgeTools crossOutTheOriginalPrice:@"￥100.00" onLabel:cell.oldPrice];
    return cell;
    }else {
        
        
        GoodsWebCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GoodsWebCollectionViewCell" forIndexPath:indexPath];
        cell.clipsToBounds = NO;
        [cell.contentView addSubview:_webView];
        cell.backgroundColor = [UIColor orangeColor];
        
        return cell;
    }
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
      NSArray * array = dataDic[@"product"];
      NSDictionary * dic = array[indexPath.row];
        GoodsDetailsViewController * goods =[[GoodsDetailsViewController alloc]init];
        goods.goodsId = [NSString stringWithFormat:@"%@",dic[@"pro_id"]];
        goods.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:goods animated:YES];
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //    第一个参数是宽，第二个参数是高 5s  1.8   6 1.6   6p
    
    if (indexPath.section==1) {
        float height;
        if (ISP5||ISP4) {
            height = 1.5;
        }else if (ISP6){
            height = 1.3;
            
        }else if (ISP6P){
            height = 1.4;
        }else {
            
            height = 1.4;
        }
        
        CGSize size=CGSizeMake((WIDTH-5)/2, (WIDTH-5)/2*height);
        
        return size;
    }else{
        
        return CGSizeMake(WIDTH, height);
    }
    
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    //上 左 下 右
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//设置水平间隙   默认10
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (section==1) {
        
        return 5;
    }else {
        
        return 0.01;
    }
}

////设置垂直间隙  默认10
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section==1) {
        
        return 5;
    }else {
        
        return 0.01;
    }
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section==0) {

        return CGSizeMake(0,WIDTH+310);
        
    }else {
        
        return CGSizeMake(0,50);
    }
    
}
//设置footer的宽度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    //第一个参数：水平滑动时footer的宽度
    //第二个参数：垂直滑动时footer的高度
    return CGSizeMake(0, 0);
}

//kind:第二个参数:区分组头,组尾
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            
            MyCenterCollectionReusableView * heardView = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MyCenterCollectionReusableView" forIndexPath:indexPath];
            heardView.backgroundColor =[UIColor groupTableViewBackgroundColor];
            
            for (UIView * view in heardView.subviews) {
                
                [view removeFromSuperview];
            }
            
            UIView * heardV =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, WIDTH+130)];
            heardV.backgroundColor =[UIColor whiteColor];
            [heardView addSubview:heardV];
            
            NSArray  * urlArray;
           
            if ([dataDic[@"smeta"] isKindOfClass:[NSArray class]]) {

                urlArray = dataDic[@"smeta"];
            }
            
            SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0,0, WIDTH, WIDTH) delegate:self placeholderImage:ImageName(@"img_list_cp_1")];
            cycleScrollView.backgroundColor =Color(229, 229, 229);
            cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
            cycleScrollView.currentPageDotColor = NavBackColor;
            cycleScrollView.type = @"normal";
            [heardV addSubview:cycleScrollView];
            cycleScrollView.imageURLStringsGroup = urlArray;
//            cycleScrollView.localizationImageNamesGroup= locatArray;
            cycleScrollView.clickItemOperationBlock = ^(NSInteger index) {
                
                TCLPhotoBrowserViewController *photo = [[TCLPhotoBrowserViewController alloc]init];
                photo.photos = urlArray;
                photo.currentPage = index;
                [self presentViewController:photo animated:YES completion:nil];
            };
            UILabel * nameLabel;
            
            if (dataDic) {
             
                nameLabel =  [self creatAllLabelFrame:CGRectMake(10, CGRectGetMaxY(cycleScrollView.frame)+10, WIDTH-20, 17) andText: dataDic[@"detail"][@"product_name"] andTextMent:NSTextAlignmentLeft andFountFrame:16 andBgColor:[UIColor clearColor] andTextColor:[UIColor blackColor] onView:heardV];
                nameLabel.numberOfLines = 2;
                [nameLabel sizeToFit];
                
                price = [self creatTypeLabelFrame:CGRectMake(12, CGRectGetMaxY(nameLabel.frame)+10, WIDTH-30, 20) andText:[NSString stringWithFormat:@"￥%@",dataDic[@"detail"][@"sale_price"]] andTextMent:NSTextAlignmentLeft andFountFrame:17 andBgColor:[UIColor clearColor] andTextColor:[UIColor redColor] onView:heardV];
                
                UILabel * normsLabel =  [self creatAllLabelFrame:CGRectMake(12, CGRectGetMaxY(price.frame)+5, WIDTH/2, 20) andText:[NSString stringWithFormat:@"￥%@",dataDic[@"detail"][@"price"]] andTextMent:NSTextAlignmentLeft andFountFrame:14 andBgColor:[UIColor clearColor] andTextColor:[UIColor grayColor]onView:heardV];
                
                [SHJudgeTools crossOutTheOriginalPrice:[NSString stringWithFormat:@"￥%@",dataDic[@"detail"][@"price"]] onLabel: normsLabel];
                
                UILabel * emsLabel =  [self creatAllLabelFrame:CGRectMake(WIDTH/2, CGRectGetMaxY(price.frame)-10, WIDTH /2-12, 20) andText:[NSString stringWithFormat:@"销量：%@  ",dataDic[@"detail"][@"virtual_num"]] andTextMent:NSTextAlignmentRight andFountFrame:14 andBgColor:[UIColor clearColor] andTextColor:[UIColor grayColor] onView:heardV];
                
                UILabel * youLabel =  [self creatAllLabelFrame:CGRectMake(0, CGRectGetMaxY(normsLabel.frame)+5, WIDTH/2, 20) andText:[NSString stringWithFormat:@"    运费：%@",dataDic[@"detail"][@"freight"]] andTextMent:NSTextAlignmentLeft andFountFrame:14 andBgColor:[UIColor clearColor] andTextColor:[UIColor grayColor]onView:heardV];
                
                UILabel * detailsLabel =  [self creatAllLabelFrame:CGRectMake(WIDTH/2, CGRectGetMaxY(normsLabel.frame)+5, WIDTH/2-10, 20) andText:[NSString stringWithFormat:@"同城配送:%@元(满%@免配送费) ",@"22",@"22"] andTextMent:NSTextAlignmentRight andFountFrame:14 andBgColor:[UIColor clearColor] andTextColor:[UIColor grayColor]onView:heardV];
            }
            
            UIView * chooseView =[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(heardV.frame)+10, WIDTH, 50)];
            
            [chooseView tapAction:^{
                
                ChooseGoodsOption = @"choose";
                [self creatGoodsTypeUi];
            }];
            chooseView.backgroundColor =[UIColor whiteColor];
            
            UILabel * chooseGg =[[UILabel alloc]initWithFrame:CGRectMake(10, 15, 120, 20)];
            chooseGg.text = @"选择商品规格";
            chooseGg.font = [UIFont systemFontOfSize:16];
            [chooseView addSubview:chooseGg];
            
            goodsTypeLabel =[[UILabel alloc]initWithFrame:CGRectMake(130, 15, WIDTH -160, 20)];
            goodsTypeLabel.text = optionNameStr;
            goodsTypeLabel.textColor = RGBa(0x666666);
            goodsTypeLabel.textAlignment = NSTextAlignmentRight;
            goodsTypeLabel.font = [UIFont systemFontOfSize:15];
            [chooseView addSubview:goodsTypeLabel];
            
            
            UIImageView * ggImage =[[UIImageView alloc]initWithFrame:CGRectMake(WIDTH-30, 10, 30, 30)];
            ggImage.image = ImageName(@"icon_information_more");
            [chooseView addSubview:ggImage];
            
            [heardView addSubview:chooseView];
            
            UIView * commentView =[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(chooseView.frame)+10, WIDTH, 50)];
            commentView.backgroundColor =[UIColor whiteColor];
            [commentView tapAction:^{
                
                
            }];
            [heardView addSubview:commentView];
            
            UILabel * commnetGg =[[UILabel alloc]initWithFrame:CGRectMake(10, 15, 120, 20)];
            commnetGg.text = @"查看评论";
            commnetGg.font = [UIFont systemFontOfSize:16];
            [commentView addSubview:commnetGg];
            
            UIImageView * comImage =[[UIImageView alloc]initWithFrame:CGRectMake(WIDTH-30, 10, 30, 30)];
            comImage.image = ImageName(@"icon_information_more");
            [commentView addSubview:comImage];
            
            UIView * detailsView =[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(commentView.frame)+10, WIDTH, 50)];
            detailsView.backgroundColor =[UIColor whiteColor];
             [heardView addSubview:detailsView];
            
            UILabel *detailsName =[[UILabel alloc]initWithFrame:CGRectMake(0, 10, WIDTH, 30)];
            detailsName.text = @"商品详情";
            detailsName.textColor = [UIColor orangeColor];
            detailsName.textAlignment = NSTextAlignmentCenter;
            detailsName.font = [UIFont systemFontOfSize:16];
            
            [detailsView addSubview:detailsName];
            
            [self creatLineView:CGRectMake(0, 49.5, WIDTH, 0.5) andOnView:detailsView];
            
            UIView * orgLine = [[UIView alloc]initWithFrame:CGRectMake(WIDTH/2-50, 49, 100, 1)];
            orgLine.backgroundColor = [UIColor orangeColor];
            [detailsView addSubview:orgLine];
            
           
            return heardView;
        }else{
            
            if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
                
                ShopFootCReusableView * footView = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"ShopFootCReusableView" forIndexPath:indexPath];
                footView.backgroundColor =[UIColor groupTableViewBackgroundColor];
                
                return footView;
                
            }else {
                
                return nil;
            }
        }
    }else {
        
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            
            MyCenterCollectionReusableView * heardView = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MyCenterCollectionReusableView" forIndexPath:indexPath];
            heardView.backgroundColor =[UIColor groupTableViewBackgroundColor];
            
            for (UIView * view in heardView.subviews) {
                
                [view removeFromSuperview];
            }
            
            UIView * titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
            titleView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            [heardView addSubview:titleView];
            
            UILabel * labele = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
            labele.text = @"---推荐---";
            labele.textAlignment = NSTextAlignmentCenter;
            [titleView addSubview:labele];
            
            return heardView;
            
        }else {
            if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
 
                ShopFootCReusableView * footView = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"ShopFootCReusableView" forIndexPath:indexPath];
                footView.backgroundColor =[UIColor groupTableViewBackgroundColor];
                
                return footView;
                
            }else {
                
                return nil;
            }
        }
    }
}

-(void)creatGoodsTypeUi{
    
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    alertBgView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    alertBgView.backgroundColor = ColorA(0, 0, 0, 0.5);
    
    scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 350, WIDTH, HEIGHT - 350 - 48)];
    scrollView.bounces = NO;
    scrollView.backgroundColor = [UIColor whiteColor];
    //关闭水平滑块：默认YES
    scrollView.showsHorizontalScrollIndicator = NO;
    //关闭垂直滑块：默认YES
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.pagingEnabled = NO;
    
    NSDictionary * dict = dataDic[@"detail"][@"option"][currayIndex];
    
    
    UILabel * price =[[UILabel alloc]initWithFrame:CGRectMake(10, 15,80, 20)];
    price.textColor = [UIColor blackColor];
    price.text = @"单价：";
    price.font = [UIFont systemFontOfSize:15];
    [scrollView addSubview:price];
    
    
    priceLabel =[[UILabel alloc]initWithFrame:CGRectMake(90, 15, 150, 20)];
    priceLabel.textColor = [UIColor orangeColor];
    priceLabel.text = [NSString stringWithFormat:@"￥%@",dict[@"price"]];
    priceLabel.font = [UIFont systemFontOfSize:16];
    
    
    
    [scrollView addSubview:priceLabel];
    
    UILabel * ggTitleLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, 50,90, 20)];
    ggTitleLabel.textColor = [UIColor blackColor];
    ggTitleLabel.text = @"规格选择";
    ggTitleLabel.font = [UIFont systemFontOfSize:15];
    [scrollView addSubview:ggTitleLabel];
    
    NSMutableArray * guiGeArray = @[].mutableCopy;
    if (guiGeArray.count>0) {
        [guiGeArray removeAllObjects];
    }

    for (NSDictionary * dic in dataDic[@"detail"][@"option"]) {

        [guiGeArray addObject:dic[@"option_name"]];
    }

    tagView = [self creatCellFitLabelOnArray:guiGeArray andBtnSel:@selector(chooseGuiGeBtn:) andViewFrame:CGRectMake(0, 70, WIDTH, 20) onView:scrollView];
    
    [self creatLineView:CGRectMake(0, CGRectGetMaxY(tagView.frame)+20, WIDTH, 0.5) andOnView:scrollView];
    
    
    UILabel * buyTitleLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(tagView.frame)+45,120, 20)];
    buyTitleLabel.textColor = [UIColor blackColor];
    buyTitleLabel.text = @"购买数量";
    buyTitleLabel.font = [UIFont systemFontOfSize:15];
    [scrollView addSubview:buyTitleLabel];
    
  
    kuCunNumber =[[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(buyTitleLabel.frame), WIDTH- 110, 20)];
    kuCunNumber.textColor = [UIColor lightGrayColor];
    kuCunNumber.text = [NSString stringWithFormat:@"剩余%@件",dict[@"stock"]];;
    kuCunNumber.font = [UIFont systemFontOfSize:14];
//    kuCunNumber.textAlignment = NSTextAlignmentRight;
    [scrollView addSubview:kuCunNumber];
    
    
    UIView * chooseNumber =[[UIView alloc]initWithFrame:CGRectMake(WIDTH-15 -140, CGRectGetMaxY(tagView.frame)+45, 140, 30)];
    chooseNumber.backgroundColor =[UIColor clearColor];
    chooseNumber.layer.borderWidth = 0.5f;
    chooseNumber.layer.borderColor =[UIColor lightGrayColor].CGColor;
    
    [scrollView addSubview:chooseNumber];
    
    [self creatShoppingAndCarBtnFrame:CGRectMake(0, 0, 40, 30) andImage:@"icon_popup_reduce_pre" andAction:@selector(subtractionBtn) andColor:[UIColor clearColor] andTitleColor:[UIColor blackColor] onView:chooseNumber];
    
    numberLabel = [[UILabel alloc]init];
    numberLabel.frame =CGRectMake(40, 0, 60, 30);
    
    numberLabel.textAlignment = NSTextAlignmentCenter;
    numberLabel.font =[UIFont systemFontOfSize:15];
    numberLabel.text = [NSString stringWithFormat:@"%d",num];
    [chooseNumber addSubview:numberLabel];
    
    [self creatShoppingAndCarBtnFrame:CGRectMake(100, 0, 40, 30) andImage:@"icon_popup_add" andAction:@selector(addBtn) andColor:[UIColor clearColor] andTitleColor:[UIColor blackColor] onView:chooseNumber];
    
    scrollView.contentSize = CGSizeMake(WIDTH , CGRectGetMaxY(chooseNumber.frame)+30);
    
    UIButton * deledateBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    deledateBtn.frame = CGRectMake(WIDTH - 50, 0, 40, 40);
    [deledateBtn setBackgroundImage:ImageName(@"icon_popup_close") forState:UIControlStateNormal];
    [deledateBtn addTarget:self action:@selector(deledateChooseView) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:deledateBtn];
    [alertBgView addSubview:scrollView];
    
    
    UIButton * sureBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.backgroundColor = [UIColor orangeColor];
    sureBtn.frame = CGRectMake(0, HEIGHT-48, WIDTH, 48);
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [alertBgView addSubview:sureBtn];
    
    [window addSubview:alertBgView];
    
    
}

-(void)sureBtnClick{  // 选择属性下边的确定
    
    NSArray * priceArray = dataDic[@"detail"][@"option"];
    NSDictionary * dic = priceArray[currayIndex];
    if ([ChooseGoodsOption isEqualToString:@"choose"]) {
        [alertBgView removeFromSuperview];
        goodsTypeLabel.text = dic[@"option_name"];
        optionNameStr = dic[@"option_name"];
        option_id = dic[@"option_id"];
    }
//    if ([ChooseGoodsOption isEqualToString:@"addCar"]) {
//        [alertBgView removeFromSuperview];
//        goodsTypeLabel.text = dic[@"option_name"];
//        option_id = dic[@"option_id"];
//        optionNameStr = dic[@"option_name"];
//        [self addShopCarGoods];  // 加车
//    }
//    if ([ChooseGoodsOption isEqualToString:@"buy"]) {
//        [alertBgView removeFromSuperview];
//        goodsTypeLabel.text = dic[@"option_name"];
//        option_id = dic[@"option_id"];
//        optionNameStr = dic[@"option_name"];
////        [self creatOrderDataRequest];   //下单
//    }
}

-(void)deledateChooseView{
    
    [alertBgView removeFromSuperview];
    
}

-(void)addCartClick:(UIButton *)btn{
    
    if (goodsTypeLabel.text.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请选择商品属性");
        return;
    }
    
    [self addShopCarGoods];
}

-(void)buyBtnClick:(UIButton *)btn{
    if (goodsTypeLabel.text.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请选择商品属性");
        return;
    }
    [self creatOrderBuyNowGoods];
}

-(void)chooseGuiGeBtn:(UIButton *)btn{
    
    currayIndex = (int)btn.tag -1000;
    
    num = 1;
    if (tagView) {
        [tagView removeFromSuperview];
    }
    
    
    NSMutableArray * guiGeArray = @[].mutableCopy;
    if (guiGeArray.count>0) {
        [guiGeArray removeAllObjects];
    }

    for (NSDictionary * dic in dataDic[@"detail"][@"option"]) {

        [guiGeArray addObject:dic[@"option_name"]];
    }
  
    tagView = [self creatCellFitLabelOnArray:guiGeArray andBtnSel:@selector(chooseGuiGeBtn:) andViewFrame:CGRectMake(0, 70, WIDTH, 20) onView:scrollView];
//
    NSArray * priceArray = dataDic[@"detail"][@"option"];
    NSDictionary * dic = priceArray[btn.tag-1000];
//
    priceLabel.text = [NSString stringWithFormat:@"￥%@",dic[@"price"]];

    kuCunNumber.text =[NSString stringWithFormat:@"%@件",dic[@"stock"]];
    
}

//减按钮
-(void)subtractionBtn {
    num--;
    if (num <=1) {
        num= 1;
    }
    numberLabel.text =[NSString stringWithFormat:@"%d",num];
}
//加按钮
-(void)addBtn {
    NSDictionary * dic = dataDic[@"detail"][@"option"][currayIndex];
    num++;
    int  allNumber = [dic[@"stock"] intValue];
    
    if (num> allNumber) {
        //            num = allNumber;
        [SHJudgeTools MBProgressHUDPromptWith:@"没有库存了！" On:self.view];
        
    }else {
        numberLabel.text =[NSString stringWithFormat:@"%d",num];
        
    }
}



//heardLabel
-(UILabel *)creatAllLabelFrame:(CGRect)cgrect andText:(NSString *)str andTextMent:(NSTextAlignment)textAlignment andFountFrame:(CGFloat)font andBgColor:(UIColor *)lor andTextColor:(UIColor *)textColor onView:(UIView *)view {
    
    UILabel * label =[[UILabel alloc]initWithFrame:cgrect];
    label.text =str;
    label.textAlignment =textAlignment;
    label.font = [UIFont systemFontOfSize:font];
    label.backgroundColor =lor;
    label.textColor =textColor;
    label.adjustsFontSizeToFitWidth =YES;
    [view addSubview:label];
    
    return label;
    
}

//预处理文字
-(UILabel *)creatTypeLabelFrame:(CGRect)cgrect andText:(NSString *)str andTextMent:(NSTextAlignment)textAlignment andFountFrame:(CGFloat)font andBgColor:(UIColor *)lor andTextColor:(UIColor *)textColor onView:(UIView *)view {
    
    UILabel * label =[[UILabel alloc]initWithFrame:cgrect];
    label.text =str;
    label.textAlignment =textAlignment;
    label.font = [UIFont systemFontOfSize:font];
    label.backgroundColor =lor;
    label.textColor =textColor;
    [view addSubview:label];
    return label;
}

-(void)creatLineView:(CGRect)rec andOnView:(UIView *)view{
    
    UIView * line =[[UIView alloc]initWithFrame:rec];
    line.backgroundColor = RGBa(0xe5e5e5);
    [view addSubview:line];
    
}

- (UIView *)creatCellFitLabelOnArray:(NSArray * )array andBtnSel:(SEL)sel andViewFrame:(CGRect)rec onView:(UIView *)view  {
    
    UIView * tagView =[[UIView alloc]initWithFrame:rec];
    
    [view addSubview: tagView];
    
    for (int i = 0; i < array.count; i++) {
        UIButton * _but = [UIButton buttonWithType:UIButtonTypeCustom];
        UIButton * upBut;
        _but.titleLabel.numberOfLines = 1;
        //        _but.layer.borderWidth = 0.8;
        //        _but.layer.borderColor = Color(245, 245, 245).CGColor;
        
        [_but setTitle:[NSString stringWithFormat:@"%@",array[i]] forState:UIControlStateNormal];
        [_but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_but setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [_but setBackgroundImage:ImageName(@"icon_botton__shop_blue") forState:UIControlStateSelected];
        _but.backgroundColor = RGBa(0xf6f6f6) ;
        
        _but.titleLabel.font = [UIFont systemFontOfSize:15];
        _but.tag = 1000 + i;
        
        //        CategoryModel * model = self.dataSource[i];
        if (i == currayIndex) {
            
            _but.selected = YES;
        }else{
            
            _but.selected = NO;
        }
        
        [_but addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
        _but.titleLabel.textAlignment = NSTextAlignmentCenter;
        CGSize size=[_but.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
        if (i!=0) {
            upBut=(id)[tagView viewWithTag:999+i];
            _but.frame=CGRectMake(CGRectGetMaxX(upBut.frame)+10, CGRectGetMinY(upBut.frame), size.width+Wt_Text,Ht_Text);
            if (CGRectGetMaxX(_but.frame) > (VIEW_W(tagView))) {
                _but.frame=CGRectMake(10, CGRectGetMaxY(upBut.frame) + H_line, size.width+Wt_Text, Ht_Text);
            }
        }else{
            _but.frame=CGRectMake(10, 10, size.width+Wt_Text, Ht_Text);
        }
        _but.layer.cornerRadius = 5.f;
        _but.clipsToBounds = YES;
        
        //        [buttonArray addObject:_but];
        
        [tagView addSubview:_but];
        if (i == array.count - 1) {
            tagView.frame = CGRectMake(VIEW_XMIN(tagView), VIEW_YMIN(tagView), VIEW_W(tagView), VIEW_YMAX(_but)+10);
        }
        _but.enabled = YES;
        _but.userInteractionEnabled = YES;
    }
    
    
    
    return tagView;
}

-(void)creatShoppingAndCarBtnFrame:(CGRect)cgrect andImage:(NSString *)imageName andAction:(SEL)action andColor:(UIColor*)col andTitleColor:(UIColor *)titleCol onView:(UIView *)view {
    
    UIButton * carBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    carBtn.frame =cgrect;
    [carBtn setBackgroundImage:ImageName(imageName) forState:UIControlStateNormal];
    [carBtn setTitleColor:titleCol forState:UIControlStateNormal];
    carBtn.titleLabel.font =[UIFont systemFontOfSize:15];
    [carBtn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:carBtn];
}

-(void)getGoodsDetailsRequest{
    
    NSDictionary * dic = @{@"pro_id":self.goodsId};
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_productDetails_api) andparameters:dic Success:^(id responseObject) {
        
        if (codeSucess) {
            
            dataDic = responseObject[@"datas"];
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        [_collectionView.mj_header endRefreshing];
        [_collectionView reloadData];
        
    } failed:^(NSError *error) {
        [_collectionView.mj_header endRefreshing];
        [_collectionView reloadData];
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
    
    
}

/**
 *  加车
 */
-(void)addShopCarGoods{
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"pro_id":self.goodsId,
                           @"quantity":[NSString stringWithFormat:@"%d",num],
                           @"option_id":option_id
                           };

    [PostNetWorking postNetWorkingStr:RequestUrlStr(add_shopCart_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        
        if (codeSucess) {
            
            SHuiMBhudTextTimeStr(@"添加购物车成功！");
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
    
}

// 结算购买

-(void)creatOrderBuyNowGoods{
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"pro_id":self.goodsId,
                           @"quantity":[NSString stringWithFormat:@"%d",num],
                           @"option_id":option_id
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(buy_itnowOrder_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        
        if (codeSucess) {
            
            SureOrderViewController * order = [[SureOrderViewController alloc]init];
            order.dataDic = responseObject[@"datas"];
            order.typeStr = @"goods";
            [self.navigationController pushViewController:order animated:YES];
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
    
}


@end
